package com.cy.jt.security.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 可以将这里的Controller看成是系统内部的一个资源对象,我们
 * 要访问此对象中的方法时需要进行权限检查
 */
@RestController
public class ResourceController {
    //添加操作
    //@PreAuthorize 注解由SpringSecurity框架提供,用于描述方法,此注解描述方法以后,再访问方法要进行权限检测
    @PreAuthorize("hasAuthority('sys:res:create')")
    @RequestMapping("/doCreate")
    public String doCreate(){
        return "create resource (insert data) ok";
    }
    //修改操作
    @PreAuthorize("hasRole('admin')")
    @RequestMapping("/doUpdate")
    public String doUpdate(){
        return "update a data success";
    }
    //查询操作
    @PreAuthorize("hasRole('admin')")
    @RequestMapping("/doSelect")
    public String doSelect(){
        return "select data success";
    }
    //删除操作
    @PreAuthorize("hasAuthority('sys:res:update')")
    @RequestMapping("/doDelete")
    public String doDelete(){
        return "delete a data success!";
    }
    //获取登录用户信息
    //1.用户登录成功以后信息
    @GetMapping("/doGetUser")
    public String doGetUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User principal =(User) authentication.getPrincipal();
        System.out.println("principal="+principal);
        return principal.getUsername()+":"+principal.getAuthorities();
    }
}
